// 完全平法数

package Leetcode;

class Solution_279_1 {
    public int numSquares(int n) {
        int m = (int) Math.sqrt(n);
        if (m * m == n)
            return 1;
        // dp[i]表示和为i的最小数量
        int[] dp = new int[n + 1];
        // 初始化
        for (int i = 1; i <= m; i++)
            dp[i * i] = 1;
        // 状态转移
        for (int i = 1; i <= n; i++) {
            if (dp[i] == 1)
                continue;
            int count = Integer.MAX_VALUE;
            for (int j = 1; j <= (int) Math.sqrt(i); j++) {
                count = Math.min(count, dp[j * j] + dp[i - j * j]);
            }
            dp[i] = count;
        }
        return dp[n];
    }
}

class Solution_279_2 {
    public int numSquares(int n) {
        // 判断是否是完全平方
        if ((int) Math.sqrt(n) * (int) Math.sqrt(n) == n)
            return 1;

        // 判断是否表示为4^k * (8m + 7)
        int m = n;
        while (m % 4 == 0) {
            m = m / 4;
        }
        if (m % 8 == 7)
            return 4;

        for (int i = 1; i * i < n; i++) {
            int k = n - i * i;
            if ((int) Math.sqrt(k) * (int) Math.sqrt(k) == k)
                return 2;
        }

        return 3;
    }
}